package com.owg.jigsaw;

import java.util.Collection;
import java.util.Iterator;

import javafx.scene.layout.Border;
import javafx.scene.layout.BorderStroke;
import javafx.scene.layout.BorderStrokeStyle;
import javafx.scene.layout.BorderWidths;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;

public class WPalette extends WPane
{
	private boolean populated = false;
	
	public WPalette(WRoot root, Collection<WBlock> palette, Pane ui)
	{
		super(root, true, ui);
		if(palette != null)
			setPalette(palette);
		if(ui != null)
			populateUI(ui);
	}
	/**Sets which blocks should be in this palette.*/
	public void setPalette(Collection<WBlock> palette)
	{
		//Remove all current elements(triggers UI remove if it has been populated)
		Iterator<WBlock> it = children.iterator();
		while(it.hasNext())
		{
			it.next();
			it.remove();
		}
		//Add all new elements(triggers UI add if it has been populated)
		for(WBlock b : palette)
		{
			children.add(b);
		}
	}
	public WPalette(WRoot root, Collection<WBlock> palette)
	{
		this(root, palette, null);
	}
	
	@Override
	protected Pane makeUI()
	{
		VBox p = new VBox(24);
		populateUI(p);
		return p;
	}

	protected void populateUI(Pane p)
	{
		if(populated)
			System.err.println("Warning: "+this+" populated twice...");
		//Make the palette itself focusable
		//This is to prevent focus from defaulting to the topmost palette block.
		p.setFocusTraversable(true);
		p.borderProperty().set(new Border(new BorderStroke(Color.TRANSPARENT, BorderStrokeStyle.NONE, null, new BorderWidths(16))));
		for(WBlock b : children)
		{
			Pane ui = b.getUI();
			p.getChildren().add(ui);
		}
		children.addListener(referencer, (param, index, oldValue, newValue) -> 
		{
			if(oldValue != null)
				p.getChildren().remove(oldValue.getUI());
			if(newValue != null)
			{
				Pane ui = newValue.getUI();
				p.getChildren().add(ui);
			}
		});
		populated = true;
	}
	
	@Override
	public BlockDropAction accepts(WBlock b)
	{
		return BlockDropAction.CANCEL;
	}
}
